<template>
  <div class="login-page">
    <div class="overlay">
      <div class="login-box">
        <h2 class="login-box h2">注册新用户</h2>
        <div class="login-content">
          <!-- 左侧：第三方登录 -->
          <div class="regist">
            <el-form :model="form" label-width="0" autocomplete="off">
              <el-form-item>
                <el-input v-model="form.username" placeholder="用户名" />
              </el-form-item>
              <el-form-item>
                <el-input v-model="form.password" type="password" placeholder="密码" />
              </el-form-item>
              <el-form-item>
                <el-input v-model="form.email" type="email" placeholder="邮箱" />
              </el-form-item>
              <el-form-item>
                <el-date-picker
                    v-model="form.birthday"
                    type="date"
                    placeholder="年 / 月 / 日"
                    format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-form>
          </div>

          <!-- 右侧：账号密码登录 -->
          <div class="account-form">
            <el-upload
              class="avatar-uploader"
              drag
              :show-file-list="false"
              accept="image/*"
              :auto-upload="false"
              :on-change="handleAvatarChange"
          >
            <template v-if="avatarPreview">
              <img :src="avatarPreview" class="avatar-preview" />
            </template>
            <template v-else>
              <i class="el-icon-plus"></i>
              <div class="el-upload__text">请上传头像</div>
            </template>
          </el-upload>

          </div>
          </div>
        </div>

        <div class="login-footer">
          <span class="span_left" @click="handleRegister">注册用户</span>
          <span class="span_right" @click="router.push('/menu')">返回登陆</span>
        </div>
      </div>
    </div>

</template>


<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import axios from 'axios';

const router = useRouter();

const form = ref({
  username: '',
  password: '',
  email: '',
  birthday: ''
});

const avatarFile = ref(null);       // 原始头像文件
const avatarPreview = ref('');      // 本地预览地址

const handleAvatarChange = (file) => {
  avatarFile.value = file.raw;
  avatarPreview.value = URL.createObjectURL(file.raw);
};

function isEmail(email) {
  const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return regex.test(email);
}

const handleRegister = async () => {
  const { username, password, email, birthday } = form.value;

  if (!username || !password) {
    ElMessage.error('用户名和密码不能为空');
    return;
  }

  if (!isEmail(email)) {
    ElMessage.error('邮箱格式不正确');
    return;
  }

  const formData = new FormData();
  formData.append('username', username);
  formData.append('password', password);
  formData.append('email', email);
  const formattedBirthday = new Date(birthday).toISOString().split('T')[0]; // 格式化为 yyyy-MM-dd
formData.append('birthday', formattedBirthday);

  //formData.append('birthday', birthday);

  if (avatarFile.value) {
    formData.append('avatar', avatarFile.value); // ⚠️ 字段名要和后端对应
  }

  try {
    const response = await axios.post('/api/users/register', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });

    const data = response.data;

    if (data.success) {
      ElMessage.success('注册成功，即将跳转...');
      form.username='';
      form.password='';
      setTimeout(() => {
        router.push('/menu');
      }, 3000);
    } else {
      ElMessage.error(data.message || '注册失败');
    }
  } catch (error) {
    ElMessage.error('网络错误，请检查网络连接');
  }
};
</script>



<style scoped>
.avatar-preview {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  object-fit: cover;
}

.el-upload__text {
  font-size: 16px;
  color: #999;
  margin-top: 10px;
}

.avatar-uploader {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center; /* 垂直居中 */
  border-radius: 12px;
  width: 100%;
  max-width: 300px;
  height: 200px; /* ✅ 高度加大，更显眼 */
  background-color: #fdfdfd;
  transition: border-color 0.3s ease;
}

.avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  object-fit: cover;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}

/* ✅ 背景全屏铺满 */
.login-page {
  position: fixed;
  inset: 0;
  background: url('@/assets/bg.png') no-repeat center center;
  background-size: cover;
  display: flex;
  justify-content: center;
  align-items: center;
}

/* ✅ 登录内容半透明白底、圆角 */
.overlay {
  background-color: rgba(255, 255, 255, 0.95);
  padding: 30px;
  border-radius: 10px;
  width: 90%;
  max-width: 800px;
}

.login-box h2 {
  color: black;
  text-align: center;
  margin-bottom: 20px;
}

.login-content {
  display: flex;
  gap: 30px;
  flex-direction: row;
  justify-content: space-between;
}

.third-party-btn {
  width: 90%;
  height: 40px;
  font-size: 14px;
  padding: 0;
}

.third-party,
.account-form {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.login-footer {
  margin-top: 20px;
  background: #555;
  color: white;
  display: flex;
  justify-content: space-between;
  padding: 10px;
  font-size: 14px;

}

.login-btn {
  width: 100%;
}

.span_left {
  width: 50%;
  display: flex;
  justify-content: center;   /* 水平居中 */
  align-items: center;       /* 垂直居中 */
}

.span_right {
  width: 50%;
  display: flex;
  justify-content: center;   /* 水平居中 */
  align-items: center;       /* 垂直居中 */

}
/* ✅ 响应式布局：小屏一列排布 */
@media (max-width: 800px) {
  .login-content {
    flex-direction: column;
  }

  .login-footer {
    flex-direction: column;
    align-items: center;
    gap: 10px;
  }
}

.span_ui {
  margin-right: 50px;
}
</style>